Scan uploaded files for malware in .net core

Jeroen Verhaeghe
2 min readApr 7, 2024

--

How can we validate and verify that upload files aren’t a threat to the system or the users?

ClamAV

ClamAV is a free and open-source antivirus and malware application.

We can install it ourselves on a VM. This has the disadvantage that we have to maintain the solution. Another option is to use a docker image.

Testing it out

The code below is not production-ready. This is just a small POC to show how we can scan an uploaded file.

For production, we upload the file somewhere and do a scan in the background. In the background process, we validate if the file doesn’t contain malware or a virus. If ClamAV is occupied or is not reachable we can then implement a retry mechanism. When the file has not been scanned yet the file will not be available to download to the end user.

In this sample, we use the nclam wrapper library.

Run clamAV instance locally:

docker run --publish 3310:3310 clamav/clamav:latest

File upload code in .net 8 with the minimal API:

app.MapPost("/upload", async Task<IResult>(HttpRequest request) =>
{

var form = await request.ReadFormAsync();

if (form.Files.Any() == false)
return Results.BadRequest("There are no files");

var file = form.Files.FirstOrDefault();

using var stream = file.OpenReadStream();
var clam = new ClamClient("localhost", 3310);
var scanResult = await clam.SendAndScanFileAsync(stream);

switch (scanResult.Result)
{
case ClamScanResults.Clean:
// File is okay
break;
case ClamScanResults.VirusDetected:
// Virus found
// Name: scanResult.InfectedFiles.First().VirusName
break;
case ClamScanResults.Error:
// Error while scanning: scanResult.RawResult);
break;
}

return Results.Ok();
})

Testing

How can we test that it works? There is something called an EICAR file. This file contains some text that most AVs use to test. This file is harmless but is flagged in most AVs as a virus/malware.

Download EICAR file: https://www.eicar.org/download-anti-malware-testfile/

In Azure Blob Storage

In Azure you can enable malware scanning for azure blob storage. This has a cost per storage account. If you store files in a blob storage and have the budget this is a valid alternative.

https://azure.microsoft.com/en-us/pricing/details/defender-for-cloud/

sources:

--

--